package com.ruoyi.project.system.controller;

import java.io.IOException;
import java.util.List;

import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.PermissionService;
import com.ruoyi.project.data.domain.WeightStation;
import com.ruoyi.project.data.service.IWeightStationService;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysNotice;
import com.ruoyi.project.system.service.ISysNoticeService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 公告 信息操作处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController
{
    @Autowired
    private ISysNoticeService noticeService;
    @Autowired
    private IWeightStationService weightStationService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 获取通知公告列表
     */
    @PreAuthorize("@ss.hasPermi('system:notice:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysNotice notice)
    {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        notice.setUserId(user.getUserId().toString());
        notice.setUserRole(user.getRoles().get(0).getRoleKey());
        if("station".equals(notice.getUserRole()) || "hs_station".equals(notice.getUserRole()) || "xq_station".equals(notice.getUserRole())
                || "jy_station".equals(notice.getUserRole()) || "yx_station".equals(notice.getUserRole())){
            // 获取场站信息
            Long stationId = user.getStationId();
            WeightStation weightStation = weightStationService.selectWeightStationById(stationId);
            if(weightStation != null){
                notice.setAreaCode(weightStation.getJurisdictionUnit());
            }
        }
        // 管理员及惠山管理员
        if (permissionService.hasRole("admin") || permissionService.hasRole("traffic_manage")){
            notice.setSearchType("1");
        }else {
            notice.setSearchType("2");
        }
        startPage();
        List<SysNotice> list = noticeService.selectNoticeList(notice);
        return getDataTable(list);
    }

    /**
     * 根据通知公告编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:notice:query')")
    @GetMapping(value = "/{noticeId}")
    public AjaxResult getInfo(@PathVariable Long noticeId)
    {
        return AjaxResult.success(noticeService.selectNoticeById(noticeId));
    }

    /**
     * 新增通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:add')")
    @Log(title = "通知公告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysNotice notice)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        notice.setCreateBy(user.getUserId().toString());
        List<SysRole> roles = user.getRoles();
        notice.setCreateRole(roles.get(0).getRoleKey());
        return toAjax(noticeService.insertNotice(notice));
    }

    /**
     * 修改通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:edit')")
    @Log(title = "通知公告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysNotice notice)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        // 判断是否管理员
        if(!SecurityUtils.isAdmin(userId)){
            // 不是管理员，只能修改自己添加的政策通知
            Long noticeId = notice.getNoticeId();
            SysNotice oldNotice = noticeService.selectNoticeById(noticeId);
            if(!oldNotice.getCreateBy().equals(userId.toString())){
                return AjaxResult.error("只能修改自己添加的政策通知！");
            }
        }
        notice.setUpdateBy(userId.toString());
        return toAjax(noticeService.updateNotice(notice));
    }

    /**
     * 删除通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:remove')")
    @Log(title = "通知公告", businessType = BusinessType.DELETE)
    @DeleteMapping("/{noticeIds}")
    public AjaxResult remove(@PathVariable Long[] noticeIds)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        // 判断是否管理员
        if(!SecurityUtils.isAdmin(userId)){
            // 不是管理员，只能修改自己添加的政策通知
            for(Long noticeId : noticeIds){
                SysNotice oldNotice = noticeService.selectNoticeById(noticeId);
                if(!oldNotice.getCreateBy().equals(userId.toString())){
                    return AjaxResult.error("只能删除自己添加的政策通知！");
                }
            }
        }
        return toAjax(noticeService.deleteNoticeByIds(noticeIds));
    }

    /**
     * 附件上传
     */
    @Log(title = "通知附件", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:notice:edit')")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {

            String path = FileUploadUtils.upload(RuoYiConfig.getNoticePath(), file);
            return AjaxResult.success(path);
        }
        return AjaxResult.error("请选择附件");
    }
}
